import { message } from 'antd';
import { connect } from 'dva';
import _ from 'lodash';
import moment from 'moment';
import React, { PureComponent } from 'react';

import PositionModalC from './positionModal';
import TurnoverModalC from './turnoverModalC';

import { AdvancedSearch, DATA_ENTRY, TableC, codeType, PrimaryGhostC } from '../../../../comps';
import config from '../../../../comps/business/tradingMarket/config';
import { exportFile, isTestRole } from '../../../../utils/commonFunc';
import dictionaryConfig from '../../../../utils/dictionaryConfig';
import { findValueByCode } from '../../../../utils/utils';

@connect(({ ValuationCheckM, loading, investmentAdviserReportM, globalM }) => ({
  ValuationCheckM,
  loading,
  investmentAdviserReportM,
  globalM,
}))
export default class PositionCheck extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      agreedData: [
        { title: '一致项', value: '0' },
        { title: '不一致项', value: '1' },
      ], // 是否一致下拉
      searchObj: {
        dataDt: moment().format('YYYY-MM-DD'),
        isAgreed: false,
      },
      currentPage: 1,
      numInPage: 10,
      total: 0,
      columns: [],
      dataSource: [],
      isReset: false, // 是否点击重置
      turnoverModal: false, // 流水对比模态框
      positionModalgetSevenTradeDate: false, // 持仓调平模态框
      turnoverData: {}, // 流水对比模态框数据
      positionData: {}, // 持仓调平模态框数据
      tradingday: moment(),
      securityTypeData: [],
      flag: isTestRole(), // 是否是测试专用角色
      sevenTradeDate: [], // 前一周交易日
    };
  }

  componentDidMount() {
    this.getSevenTradeDate().then(() => {
      this.props.dispatch({
        type: 'investmentAdviserReportM/getTradingDay',
        payload: { type: '1' },
        callback: (data) => {
          this.setState(
            {
              tradingday: data,
              searchObj: { ...this.state.searchObj, dataDt: moment(data).format('YYYY-MM-DD') },
            },
            () => {
              this.getTableData();
            },
          );
        },
      });
    });

    const data = _.cloneDeep(dictionaryConfig.holdTypeTree);
    data.forEach((i) => {
      if (i.value == '16;17') {
        delete i.children;
      }
      if (i.value == '1;101;201') {
        i.value = '1';
      }
      if (i.value == '9;2') {
        i.children[0].value = '9';
      }
    });
    this.setState({ securityTypeData: data });
    //  更新未读消息---用于用户视图数据
    this.props.dispatch({
      type: 'ValuationCheckM/updateUnreadDate',
      payload: {
        msgType: '3',
      },
    });
  }

  // 获取近一周的交易日
  getSevenTradeDate = () => {
    // 对于普通租户，只能允许对交易日为近一周的日期的进行调仓和回溯；对于测试专用(公共)角色，不做限制，可以点击任何一天
    // isTestRole(), //是否是测试专用角色
    const promise = new Promise((resolve) => {
      if (!isTestRole()) {
        this.props.dispatch({
          type: 'investmentAdviserReportM/getSevenTradeDate',
          payload: {},
          callback: (data) => {
            this.setState(
              {
                sevenTradeDate: data || [],
              },
              () => {
                // eslint-disable-next-line no-lone-blocks
                {
                  resolve();
                }
              },
            );
          },
        });
      } else {
        resolve();
      }
    });
    return promise;
  };

  // 查询表格数据
  getTableData = () => {
    const { searchObj, currentPage, numInPage, sevenTradeDate } = this.state;
    const {
      ValuationCheckM: { positionColumns },
    } = this.props;

    this.props.dispatch({
      type: 'ValuationCheckM/getPositionTableData',
      payload: {
        ...searchObj,
        userId: localStorage.getItem('antd-pro-userId'),
        page: currentPage,
        pageSize: numInPage,
      },
      callback: (type, data) => {
        const newColumns = this.changeColumns(positionColumns);
        if (type == 'success') {
          // 非测试专员 只能点击交易日前一周的数据 ；测试专员不做限制
          data.dataSource?.map((item) => {
            // flag==1 可点击 2不可点击
            item.flag = !this.state.flag ? (sevenTradeDate.includes(moment(item.dataDt).format('YYYYMMDD')) ? 1 : 2) : 1;
          });
          this.setState({
            columns: newColumns,
            dataSource: data.dataSource,
            total: data.pageInfo && data.pageInfo.total,
          });
        } else {
          this.setState({
            columns: newColumns,
            dataSource: [],
            total: 0,
          });
        }
      },
    });
  };

  // 更改表头
  changeColumns = (columns) => {
    const {
      globalM: {
        dataDictionary: { ENTRUSTED_INVESTMENT_HOLD_ATTRCODE = [] },
      },
    } = this.props;

    if (columns && columns.length) {
      columns.map((item) => {
        if (item.key == 'operate') {
          item.operates = [
            {
              title: '流水对比',
              onClick: (record) => {
                this.turnoverContrast(record);
              },
            },
            {
              title: '持仓调平',
              onClick: (record) => {
                this.positionLeveling(record);
              },
              rules: {
                disabled: { items: [{ key: 'flag', value: [2], relation: ['='] }], relation: 'or' },
              },
            },
            {
              title: '回溯',
              isPopWindow: true,
              PopWindowText: '确定回溯？',
              onClick: (record) => {
                this.Backtracking(record);
              },
            },
          ];
        }
        // 交易属性
        if (item.key == 'trdAttr') {
          item.render = (text) => findValueByCode(text, ENTRUSTED_INVESTMENT_HOLD_ATTRCODE);
        }
        if (item.key == 'exchangeCode') {
          item.render = (text) => {
            // eslint-disable-next-line no-shadow
            const findvalue = config.filter((item) => item.selfValue == text);
            if (findvalue && findvalue.length > 0) {
              return findvalue[0].title;
            }
            return '--';
          };
        }
      });
    }
    return columns;
  };

  // 响应回溯
  Backtracking = (record) => {
    this.props.dispatch({
      type: 'ValuationCheckM/Backtracking',
      payload: { compareId: record.compareId },
      callback: (data) => {
        if (data) {
          this.getTableData();
        }
      },
    });
  };

  // 流水对比
  turnoverContrast = (record) => {
    this.setState({
      turnoverModal: true,
      turnoverData: record,
    });
  };

  // 持仓调平
  positionLeveling = (record) => {
    // 【资产类型】为“回购”，当【系统数量】>【财务数量】时，用户点击“持仓调平”按钮，不弹出模态框，消息提示“系统不支持回购调减，请联系管理员进行数据调整。”
    if (['3', '4', '5', '6', '13', '14', '32', '33'].includes(record.type) && record.xtsl > record.cwsl) {
      message.info('系统不支持回购调减，请联系管理员进行数据调整。');
      return;
    }
    this.setState({
      positionModal: true,
      positionData: record,
    });
  };

  // 模态框确定
  onOk = () => {
    this.setState({
      turnoverModal: false,
      positionModal: false,
    });
    this.getTableData();
  };

  // 模态框取消
  onCancel = () => {
    this.setState({
      turnoverModal: false,
      positionModal: false,
    });
  };

  // 查询表格数据
  queryTableList = (e) => {
    const tempObj = {};
    // eslint-disable-next-line guard-for-in,no-unused-vars
    for (const k in e) {
      if (k == 'dataDt') {
        tempObj[k] = e[k].format('YYYY-MM-DD');
      } else {
        tempObj[k] = e[k];
      }
      if (k == 'isAgreed') {
        if (e[k] == '0') {
          tempObj[k] = true;
        } else if (e[k] == '1') {
          tempObj[k] = false;
        }
      }
    }
    if (e && !e.dataDt) {
      tempObj.dataDt = null;
      message.warning('请选择查询日期!');
    } else {
      tempObj.exchangeCode = undefined;

      this.setState(
        {
          searchObj: tempObj,
          isReset: false,
          currentPage: 1,
          numInPage: 10,
        },
        () => {
          this.getTableData();
        },
      );
    }
  };

  // 表格页码排序改变调用
  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    const { isReset } = this.state;
    if (isReset) {
      // 判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      return;
    }
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.getTableData();
      },
    );
  };

  // 导出
  export = () => {
    exportFile('api/v1/amboCompare/exportHoldDifference', this.state.searchObj);
  };

  render() {
    const { columns, dataSource, total, currentPage, numInPage, turnoverModal, positionModal, turnoverData, positionData } = this.state;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'dataDt',
          title: '日期',
          type: DATA_ENTRY.SINGLEDATE,
          initialValue: moment(this.state.tradingday),
          disableEnd: moment(this.state.tradingday).add(1, 'days'),
        },
        {
          dataIndex: 'isAgreed',
          title: '一致性',
          type: DATA_ENTRY.SELECT,
          dataSource: this.state.agreedData,
          allowClear: true,
          initialValue: '1',
        },
        {
          dataIndex: 'securityType',
          title: '资产类型',
          type: DATA_ENTRY.TREESELECT,
          dataSource: this.state.securityTypeData,
          allowClear: true,
        },
        {
          dataIndex: 'cpCode',
          title: '产品',
          type: DATA_ENTRY.PRODUCTLIST,
          allowClear: true,
          tradeModel: ['BOOKKEEPING_MODE', 'COMMAND_MODE'],
          verificationModeGZ: '0', // 表示有估值
          positionBody: true,
        },
        {
          dataIndex: 'zqCode',
          title: '证券代码',
          type: DATA_ENTRY.SECURITIESCODE,
          allowClear: true,
          codeType: codeType.positioned,
          positionBody: true,
        },
      ],
      // 点击查询按钮
      onQuery: (e) => {
        this.queryTableList(e);
      },
      onClear: () => {
        // 点击重置按钮
        this.setState({
          searchObj: {},
          isReset: true,
        });
      },
    };
    return (
      <div>
        <div style={{ marginBottom: '10px' }}>
          {/* eslint-disable-next-line react/jsx-props-no-spreading */}
          <AdvancedSearch {...searchProps} />
        </div>
        <div style={{ textAlign: 'right', marginBottom: '10px' }}>
          <PrimaryGhostC title='导出' onClick={this.export} />
        </div>
        <TableC
          columns={columns}
          loading={this.props.loading.effects['ValuationCheckM/getPositionTableData'] == true}
          dataSource={dataSource}
          current={currentPage}
          total={total}
          pageSize={numInPage}
          rowKey='id'
          scroll={{ x: 'max-content' }}
          selfScrollY
          onChange={this.handleTableChange}
        />
        {turnoverModal && <TurnoverModalC isVisible={turnoverModal} modalData={turnoverData} onCancel={this.onCancel} />}
        {positionModal && <PositionModalC isVisible={positionModal} modalData={positionData} onOk={this.onOk} onCancel={this.onCancel} />}
      </div>
    );
  }
}
